package com.neo.tiny.middle.socket.websocket;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.neo.tiny.business.iot.api.IotDeviceApi;
import com.neo.tiny.business.iot.enums.RelaySwitchStatus;
import com.neo.tiny.business.iot.vo.IotDeviceInfoReq;
import com.neo.tiny.middle.socket.websocket.util.IotWebSocketMsgSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/8/19 20:12
 */
@Slf4j
@ServerEndpoint("/websocket/iot/{deviceId}")
@Component
public class IoTWebSocketServer {


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
        log.info("IoT创建连接：{}", deviceId);
        IotWebSocketMsgSender.addClient(deviceId, session);
        IotDeviceApi iotDeviceApi = SpringUtil.getBean(IotDeviceApi.class);
        iotDeviceApi.addDevice(deviceId);
    }

    /**
     * 接收消息
     *
     * @param session  会话
     * @param deviceId 标识
     */
    @OnMessage
    public void onMessage(Session session, String message, @PathParam("deviceId") String deviceId) {
        log.info("IoT收到:{},的消息：{}", deviceId, message);
//        WebSocketMsgUtil.sendMsg(deviceId, message + "！");
        IotDeviceApi deviceApi = SpringUtil.getBean(IotDeviceApi.class);
        IotDeviceInfoReq req = JSONUtil.toBean(message, IotDeviceInfoReq.class);
        deviceApi.updateDeviceInfo(req);
        IotWebSocketMsgSender.changeIotClientStatus(req.getDeviceId(), RelaySwitchStatus.matchAction(req.getLedStatus()));
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("deviceId") String deviceId) {
        log.info("IoT关闭连接");
        IotWebSocketMsgSender.removeClient(deviceId);
    }

    /**
     * @param session 会话
     */
    @OnError
    public void onError(Session session, @PathParam("deviceId") String deviceId, Throwable error) {
        IotWebSocketMsgSender.removeClient(deviceId);
        log.error("IoTWebsocket发生错误:{}", error.getMessage());
        error.printStackTrace();
    }

}